/*
 * Copyright (c) 2021/4/23 . All Rights Reserved.
 */
package com.ml.customannotation.aop.customAnnotation;

import lombok.extern.slf4j.Slf4j;


/**
 * @author: z Date: 2021/4/23 Time: 2:34 下午
 * @version: 1.0.0
 */
@Slf4j
public abstract class BizTemplate<T> {

    protected abstract void checkParams();

    protected abstract T process() throws Throwable;

    protected void afterProcess() {
    }

    protected void onSuccess() {
    }

    protected void onError(Throwable e) {
    }

    public T execute() {
        try {
            checkParams();
        } catch (IllegalArgumentException e) {
            if (log.isDebugEnabled()) {
                log.debug("check param failed", e);
            }
            throw e;
        }

        try {
            T result = process();
            onSuccess();
            return result;
        } catch (BizException biz) {
            log.debug("biz error while execute, " + biz.getMessage(), biz);
            onError(biz);
            throw new RuntimeException(biz.getMessage(), biz);
        } catch (Throwable e) {
            log.warn("unexpected error while execute, " + e.getMessage(), e);
            onError(e);
            throw new RuntimeException(e.getMessage(), e);
        } finally{
            afterProcess();
        }
    }


}